package com.uduemc.biso.module.basic.service.common.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.core.common.dto.CBMastermanageAppend;
import com.uduemc.biso.core.common.extities.CMasterUserData;
import com.uduemc.biso.core.extities.center.MasterUser;
import com.uduemc.biso.module.basic.service.common.mapper.CMasterUserDataMapper;
import com.uduemc.biso.module.basic.service.common.service.CMasterUserService;
import com.uduemc.biso.module.basic.service.service.MasterUserService;

@Service
public class CMasterUserServiceImpl implements CMasterUserService {

	@Autowired
	private MasterUserService masterUserServiceImpl;

	@Autowired
	private CMasterUserDataMapper cMasterUserDataMapper;

	@Override
	@Transactional
	public MasterUser userAppend(CBMastermanageAppend cBMastermanageAppend) {
		MasterUser masterUser = cBMastermanageAppend.getMasterUser();
		if (StringUtils.isEmpty(masterUser.getPasswordHash())) {
			throw new RuntimeException("写入数据库中的密码不能为空！");
		}
		String username = masterUser.getUsername();
		MasterUser findByUsername = masterUserServiceImpl.findByUsername(username);
		if (findByUsername != null) {
			throw new RuntimeException("用户名已经存在无法新增用户！");
		}
		String numberKey = masterUser.getNumberKey();
		if (StringUtils.isEmpty(numberKey)) {
			// 创建一个 numberKey
			String createNumberKey = masterUserServiceImpl.getCreateNumberKey();
			masterUser.setNumberKey(createNumberKey);
		} else {
			// 验证当前的 numberKey 是否存在
			MasterUser findByNumberKey = masterUserServiceImpl.findByNumberKey(numberKey);
			if (findByNumberKey != null) {
				throw new RuntimeException("数字账号已经存在，无法创建新用户！");
			}
		}
		// 写入数据 master_user 表当中
		MasterUser insert = masterUserServiceImpl.insert(masterUser);
		return insert;
	}

	@Override
	public PageInfo<CMasterUserData> userInfo(String username, String numberKey, short status, short loginNode,
			int pageNumber, int pageSize, String orderByString) {
		PageHelper.startPage(pageNumber, pageSize);
		List<CMasterUserData> findCMasterDataInfos = cMasterUserDataMapper.findCMasterDataInfos(username, numberKey,
				status, loginNode, orderByString);
		return new PageInfo<>(findCMasterDataInfos);
	}

}
